<?php
	require_once '../lib/controller.php';

	class action extends controller
	{
		function do_get()
		{
			$db = $this->module('lib.db');
			$sql = "select id,cname,parent_cname from meye_site_cate";
			$data = $db->query($sql, 'all');
			$cate_list = $this->gen_cate_list($data, 1);
			$data['cate_list'] = $cate_list;
			if( isset($this->get['uri']) )
			{
				$data['uri'] = $this->get['uri'];
			}

			$this->view('www.site_add', $data);
		}

		public function do_post()
		{
			$myurl = parse_url($this->post['url']);
			$ip = gethostbyname($myurl['host']);
			if( $ip == $myurl['host'] )
			{
				$this->msg('站点不存在。', 0, 'site_add.php');
			}

			$db = $this->module('lib.db');
			$site = $this->module('biz.site');
			if( $site->add_site() )
			{
				$this->msg($site->msg, 3, 'site_add.php');
			}
			else
			{
				$this->msg($site->msg);
			}
		}

		function check_privileges()
		{
			if( ! isset($this->session['user_id']) )
			{
				$this->msg('请先登录', 3, 'login.php');
				return false;
			}else{
				return true;
			}
		}

		public function check_post()
		{
			if( empty($this->post['site_cate_id']) )
			{
				$this->msg('站点类别错误');
				return false;
			}
			if( strlen($this->post['site']) > 24 || strlen($this->post['site']) < 6 )	//utf8字3个字符
			{
				$this->msg('站点名称格式不正确');
				return false;
			}
			$tool = $this->module('lib.tool');
			if( ! $tool->check_url($this->post['url']) )
			{
				$this->msg('网址格式不正确');
				return false;
			}
			return true;
		}

		function tool_map($data)
		{
			$ret = array();
			foreach($data as $key=>$row)
			{
				$ret[$row['parent_cname']][] = array($row['id'], $row['cname']);
			}

			return $ret;
		}

		function gen_cate_list($data, $curr_cate_id)
		{
			$data = $this->tool_map($data);
			$optg = '';
			foreach($data as $parent_cname=>$arr)
			{
				$optg .= '<optgroup label="' . $parent_cname . '">';
				$opt = '';
				foreach( $arr as $row )
				{
					if( $curr_cate_id == $row[0] )
					{
						$sel = 'selected';
					}else{
						$sel = '';
					}
					$opt .= '<option value="' . $row[0] . '" ' . $sel . '>' . $row[1] . '</option>';
				}
				$optg .= $opt . '</optgroup>';
			}

			return $optg;
		}
	}

	$action = new action();
	$action->run();
?>